<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;

use Org\Util\Date;
use Think\Controller;
//use Com\Slog;

//use Com\Wechat;

class PatientController extends Controller{
    public function index(){
        if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])
        {
            $ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
        }
        elseif ($HTTP_SERVER_VARS["HTTP_CLIENT_IP"])
        {
            $ip = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
        }
        elseif ($HTTP_SERVER_VARS["REMOTE_ADDR"])
        {
            $ip = $HTTP_SERVER_VARS["REMOTE_ADDR"];
        }
        elseif (getenv("HTTP_X_FORWARDED_FOR"))
        {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        }
        elseif (getenv("HTTP_CLIENT_IP"))
        {
            $ip = getenv("HTTP_CLIENT_IP");
        }
        elseif (getenv("REMOTE_ADDR"))
        {
            $ip = getenv("REMOTE_ADDR");
        }
        else
        {
            $ip = "Unknown";
        }
//echo "你的IP:".$ip ;
        $time= date("Hi",time());
        if ($time>"1930"){
            echo "kldsjhafksjd";
        }

        die($time);


    }
    public function sendmessage_test(){
        //读取post过来的参数
        $postdata = urldecode(file_get_contents("php://input"));
        $requestdata = json_decode($postdata,TRUE);
        $md5str=$requestdata["md5str"];
        $wxh  = $this->checkuser($md5str);

        $openid = $requestdata["openid"];
        $testname = $requestdata["testname"];
        $testdate = $requestdata["testdate"];
        $this->sendmessage_jiacha($wxh,$openid,$testname,$testdate);
        die('ok');
    }
    //发送检查结果通知

    public function sendmessage_jiacha($wxh,$openid,$testname,$pati_name,$testdate){
        //记录发送消息日志供查询
        $logdata = D('wx_message_mzjc')->create();
        $logdata['wxh']= $wxh;
        $logdata['openid']= $openid;
        $logdata['pati_name']= $pati_name;
        $logdata['testname']= $testname;
        $logdata['testdate']= $testdate;

        $logdata['logtime']= time();
        $logid = D('wx_message_mzjc')->add($logdata);


        $access = $this->getAccess($wxh);
        $patients = D('wx_patient')->where("weixinhao='$wxh' and openid='".$openid."' and flag='1' ")->select();
        $templetes =D('wx_all_templete')->where("weixinhao='$wxh' and templete_key='key_jiancha'")->select();
        if (count($templetes)==0){
            $logdatas = D('wx_message_mzjc')->where("id=$logid")->select();
            $logdata = $logdatas[0];
            $logdata['note']= '没有找到模版';
            D('wx_message_mzjc')->save($logdata);

            //没有找到指定模版
            return;
        }
        $templete_id=$templetes[0]["templete_id"];
        $first=$templetes[0]["first"];
        $remark=$templetes[0]["remark"];

        if (count($patients)>0){
            $data = Array('touser'=>$openid,
                'template_id'=>$templete_id,
                'topcolor'=>'#FF0000',
                'url'=>'',
                'data'=>Array(
                    'first'   =>Array("color"=>"#173177","value"=>$first),
                    'keyword1'=>Array("color"=>"#173177","value"=>$testname),
                    'keyword2'=>Array("color"=>"#173177","value"=>$pati_name),
                    'keyword3'=>Array("color"=>"#173177","value"=>$testdate),
                    'remark'  =>Array("color"=>"#173177","value"=>$remark)
                ));
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access;
            $jsondata = json_encode($data);

            $json=self::http_request_json_post($url,$jsondata);
            $returndata = json_decode($json,true);
            //需要将发消息的记录和结果保存至日志数据库
            $logdatas = D('wx_message_mzjc')->where("id=$logid")->select();
            $logdata = $logdatas[0];
            $logdata['note']= 'success';
            $logdata['remark']= $remark;
            D('wx_message_mzjc')->save($logdata);

            return;
        } else {
          $logdatas = D('wx_message_mzjc')->where("id=$logid")->select();
          $logdata = $logdatas[0];
          $logdata['note']= '没有找到患者';
          $logdata['remark']= $remark;
          D('wx_message_mzjc')->save($logdata);

        //没有找到患者
            return;
        }
    }
    //发送缴费成功通知
    //发送缴费成功通知
    //发送缴费成功通知
    //发送缴费成功通知
    //发送缴费成功通知
    //发送缴费成功通知

    public function sendmessage_mzjf($wxh,$openid,$pati_name,$piaohao,$je,$doctor,$keshi,$yiyuan,$jfrq,$remark){

        //记录发送消息日志供查询
        $logdata = D('wx_message_mzjf')->create();
        $logdata['wxh']= $wxh;
        $logdata['openid']= $openid;
        $logdata['pati_name']= $pati_name;
        $logdata['piaohao']= $piaohao;
        $logdata['je']= $je;
        $logdata['doctor']= $doctor;
        $logdata['keshi']= $keshi;
        $logdata['yiyuan']= $yiyuan;
        $logdata['jfrq']= $jfrq;
        $logdata['remark']= $remark;

        $logdata['logtime']= time();
        $logid = D('wx_message_mzjf')->add($logdata);


        $access = $this->getAccess($wxh);

        $patients = D('wx_patient')->where("weixinhao='$wxh' and openid='".$openid."' and flag='1' ")->select();
        $templetes =D('wx_all_templete')->where("weixinhao='$wxh' and templete_key='key_mzjf'")->select();
        if (count($templetes)==0){
            $logdatas = D('wx_message_mzjf')->where("id=$logid")->select();
            $logdata = $logdatas[0];
            $logdata['note']= '没有找到模版';
            D('wx_message_mzjf')->save($logdata);
            //没有找到指定模版
            return;
        }
        $templete_id=$templetes[0]["templete_id"];
        $first=$templetes[0]["first"];
        $remark_adds=$templetes[0]["remark"]; //读取模版里的remark

        if (count($patients)>0){
            $data = Array('touser'=>$openid,
                'template_id'=>$templete_id,
                'topcolor'=>'#FF0000',
                'url'=>'',
                'data'=>Array(
                    'first'   =>Array("color"=>"#173177","value"=>$first),
                    'keynote1'=>Array("color"=>"#173177","value"=>$pati_name),
                    'keynote2'=>Array("color"=>"#173177","value"=>$piaohao),
                    'keynote3'=>Array("color"=>"#173177","value"=>$je),
                    'keynote4'=>Array("color"=>"#173177","value"=>$doctor),
                    'keynote5'=>Array("color"=>"#173177","value"=>$keshi),
                    'keynote6'=>Array("color"=>"#173177","value"=>$yiyuan),
                    'keynote7'=>Array("color"=>"#173177","value"=>$jfrq),
                    'remark'  =>Array("color"=>"#173177","value"=>"$remark $remark_adds")
                ));
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access;
            $jsondata = json_encode($data);

            $json=self::http_request_json_post($url,$jsondata);
            $returndata = json_decode($json,true);
            //需要将发消息的记录和结果保存至日志数据库
            $logdatas = D('wx_message_mzjf')->where("id=$logid")->select();
            $logdata = $logdatas[0];
            $logdata['note']= 'success';
            D('wx_message_mzjf')->save($logdata);
            return;
        } else {
            $logdatas = D('wx_message_mzjf')->where("id=$logid")->select();
            $logdata = $logdatas[0];
            $logdata['note']= '没有找到患者';
            D('wx_message_mzjf')->save($logdata);

            //没有找到患者
            return;
        }
    }
    //发送退费成功通知

    public function sendmessage_mztf($wxh,$openid,$piaohao,$je,$tfrq,$remark){

        //记录发送消息日志供查询
        $logdata = D('wx_message_mztf')->create();
        $logdata['wxh']= $wxh;
        $logdata['openid']= $openid;
        $logdata['piaohao']= $piaohao;
        $logdata['je']= $je;
        $logdata['tfrq']= $tfrq;
        $logdata['remark']= $remark;

        $logdata['logtime']= time();
        $logid = D('wx_message_mztf')->add($logdata);



        $access = $this->getAccess($wxh);

        $patients = D('wx_patient')->where("weixinhao='$wxh' and openid='".$openid."' and flag='1' ")->select();
        $templetes =D('wx_all_templete')->where("weixinhao='$wxh' and templete_key='key_mztf'")->select();
        if (count($templetes)==0){
            $logdatas = D('wx_message_mztf')->where("id=$logid")->select();
            $logdata = $logdatas[0];
            $logdata['note']= '没有找到模版';
            D('wx_message_mztf')->save($logdata);

            //没有找到指定模版
            return;
        }
        $templete_id=$templetes[0]["templete_id"];
        $first=$templetes[0]["first"];
        $remark_adds=$templetes[0]["remark"]; //读取模版里的remark

        if (count($patients)>0){
            $data = Array('touser'=>$openid,
                'template_id'=>$templete_id,
                'topcolor'=>'#FF0000',
                'url'=>'',
                'data'=>Array(
                    'first'   =>Array("color"=>"#173177","value"=>$first),
                    'keynote1'=>Array("color"=>"#173177","value"=>$piaohao),  //票号
                    'keynote3'=>Array("color"=>"#173177","value"=>$tfrq),    //退费时间
                    'keynote4'=>Array("color"=>"#173177","value"=>$je),         //金额
                    'keynote5'=>Array("color"=>"#173177","value"=>''),     //到帐时间
                    'remark'  =>Array("color"=>"#173177","value"=>"$remark $remark_adds")
                ));
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access;
            $jsondata = json_encode($data);

            $json=self::http_request_json_post($url,$jsondata);
            $returndata = json_decode($json,true);

            //需要将发消息的记录和结果保存至日志数据库
            $logdatas = D('wx_message_mztf')->where("id=$logid")->select();
            $logdata = $logdatas[0];
            $logdata['note']= 'success';
            D('wx_message_mztf')->save($logdata);

            return;
        } else {
            $logdatas = D('wx_message_mztf')->where("id=$logid")->select();
            $logdata = $logdatas[0];
            $logdata['note']= '没有找到患者';
            D('wx_message_mztf')->save($logdata);
            //没有找到患者
            return;
        }
    }
    //发送取药通知

    public function sendmessage_quyao($wxh,$openid,$sick_no,$pati_name,$pres_name,$je){
        //记录发送消息日志供查询
        $logdata = D('wx_message_mzqy')->create();
        $logdata['wxh']= $wxh;
        $logdata['openid']= $openid;
        $logdata['sick_no']= $sick_no;
        $logdata['pati_name']= $pati_name;
        $logdata['pres_name']= $pres_name;
        $logdata['je']= $je;

        $logdata['logtime']= time();
        $logid = D('wx_message_mzqy')->add($logdata);


        $access = $this->getAccess($wxh);

        $patients = D('wx_patient')->where("weixinhao='$wxh' and openid='".$openid."' and flag='1' ")->select();
        $templetes =D('wx_all_templete')->where("weixinhao='$wxh' and templete_key='key_quyao'")->select();
        if (count($templetes)==0){
            $logdatas = D('wx_message_mzqy')->where("id=$logid")->select();
            $logdata = $logdatas[0];
            $logdata['note']= '没有找到模版';
            D('wx_message_mzqy')->save($logdata);

            //没有找到指定模版
            return;
        }
        $templete_id=$templetes[0]["templete_id"];
        //slog("templeteid=$templete_id");
        //slog("openid=$openid");
        $first=$templetes[0]["first"];
        $remark=$templetes[0]["remark"]; //读取模版里的remark

        if (count($patients)>0){
            $data = Array('touser'=>$openid,
                'template_id'=>$templete_id,
                'topcolor'=>'#FF0000',
                'url'=>'',
                'data'=>Array(
                    'first'   =>Array("color"=>"#173177","value"=>$first),
                    'keyword1'=>Array("color"=>"#173177","value"=>$pati_name),  //患者名
                    'keyword2'=>Array("color"=>"#173177","value"=>$sick_no),  //病案号
                    'keyword3'=>Array("color"=>"#173177","value"=>$pres_name),  //处方名
                    'keyword4'=>Array("color"=>"#173177","value"=>$je),  //金额
                    'keyword5'=>Array("color"=>"#173177","value"=>''),  //窗口位置
                    'remark'  =>Array("color"=>"#173177","value"=>$remark)
                ));
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access;
            $jsondata = json_encode($data);

            $json=self::http_request_json_post($url,$jsondata);
            $returndata = json_decode($json,true);

            $logdatas = D('wx_message_mzqy')->where("id=$logid")->select();
            $logdata = $logdatas[0];
            $logdata['remark']= $remark;
            $logdata['note']= 'success';
            D('wx_message_mzqy')->save($logdata);

            //需要将发消息的记录和结果保存至日志数据库
            return;
        } else {
            $logdatas = D('wx_message_mzqy')->where("id=$logid")->select();
            $logdata = $logdatas[0];
            $logdata['remark']= $remark;
            $logdata['note']= '没有找到患者';
            D('wx_message_mzqy')->save($logdata);
            //没有找到患者
            return;
        }
    }


    //
    //发送预约成功通知
    //

    public function sendmessage_yygh($wxh,$openid,$pati_name,$sick_no,$keshi,$doctorname,$bookdate){
        $access = $this->getAccess($wxh);

        $patients = D('wx_patient')->where("weixinhao='$wxh' and openid='".$openid."' and flag='1' ")->select();
        $templetes =D('wx_all_templete')->where("weixinhao='$wxh' and templete_key='key_yygh'")->select();
        if (count($templetes)==0){
            //没有找到指定模版
            return;
        }
        $templete_id=$templetes[0]["templete_id"];
        $first=$templetes[0]["first"];
        $remark="您的预约号为".$keshi."。".$templetes[0]["remark"];


        if (count($patients)>0){
            $data = Array('touser'=>$openid,
                'template_id'=>$templete_id,
                'topcolor'=>'#FF0000',
                'url'=>'',
                'data'=>Array(
                    'first'   =>Array("color"=>"#173177","value"=>$first),
                    'keyword1'=>Array("color"=>"#173177","value"=>$pati_name),
                    'keyword2'=>Array("color"=>"#173177","value"=>$sick_no),
                    'keyword3'=>Array("color"=>"#173177","value"=>""),
                    'keyword4'=>Array("color"=>"#173177","value"=>$doctorname),
                    'keyword5'=>Array("color"=>"#173177","value"=>$bookdate),
                    'remark'  =>Array("color"=>"#173177","value"=>$remark)
                ));
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access;
            $jsondata = json_encode($data);

            $json=self::http_request_json_post($url,$jsondata);
            $returndata = json_decode($json,true);
            //需要将发消息的记录和结果保存至日志数据库
            return;
        } else {
            //没有找到患者
            return;
        }
    }
    //
    //发送所有预约通知
    //

    public function sendmessage_all_yygh($bookdate){
        $bookings = D('wx_bookinglist')->where("bookingdate='$bookdate'")->select();
        foreach ($bookings as $booking) {
            $sick_no = $booking['sick_no'];
            $patients = D('wx_patient')->where("sick_no='".$sick_no."' and flag='1' ")->select();
            if (count($patients)>0){
                $wxh = $patients[0]['weixinhao'];
                $openid = $patients[0]['openid'];
                $pati_name = $patients[0]['pati_name'];
                $ordernumber = $patients[0]['ordernumber'];
                $this->sendmessage_yygh($wxh,$openid,$pati_name,$sick_no,$ordernumber,'曹开镛',$bookdate);
            }
        }
        return;
    }

    /*
	    处理数据同步请求
	    1）从post过来的数据取要发送的消息发送给微信服务器
	    2）从post过来的数据取同步时间
	    3）数据库查询同步时间以后的新增绑定数据和取消绑定数据，和当前服务器时间打包返回

	*/
    public function syncdata(){
        //读取post过来的参数
        $postdata = urldecode(file_get_contents("php://input"));
        $requestdata = json_decode($postdata,TRUE);
        if (count($requestdata) ==0){
            $result = array ('result'=>'0','message'=>"无数据提交,didn't have data commit",'synctime'=>time());
            exit(json_encode($result));
        }

        $md5str=$requestdata["md5str"];
        $wxh  = $this->checkuser($md5str);
        $appinfo=D('wx_appinfo')->where("weixinhao='$wxh'")->find();
        $appinfo["serverip"]=$this->get_sync_ip();
        D('wx_appinfo')->save($appinfo);


        $messages = $requestdata["messages"];
        $synctime = $requestdata["synctime"];
        foreach ($messages as $message) {
            $message_type = $message["message_type"];
            if ($message_type=="HY") { //发送化验结果通知
                $open_id = $message["open_id"];
                $pati_name = $message["pati_name"];
                $treatname = $message["treatname"];
                $treatdate = $message["treatdate"];
                $this->sendmessage_jiacha($wxh,$open_id,$treatname,$pati_name,$treatdate);
            } elseif ($message_type=="JF"){ //发送收费成功通知
                $open_id = $message["open_id"];
                $pati_name = $message["pati_name"];
                $piaohao = $message["piaohao"];
                $je = $message["je"];
                $doctor = $message["doctor"];
                $keshi = $message["keshi"];
                $yiyuan = $message["yiyuan"];
                $jfrq = $message["jfrq"];
                $remark = $message["remark"];
                $this->sendmessage_mzjf($wxh,$open_id,$pati_name,$piaohao,$je,$doctor,$keshi,$yiyuan,$jfrq,$remark);
            } elseif ($message_type=="TF"){//发送退费成功通知
                $open_id = $message["open_id"];
                $piaohao = $message["piaohao"];
                $je = $message["je"];
                $tfrq = $message["tfrq"];
                $remark = $message["remark"];
                $this->sendmessage_mztf($wxh,$open_id,$piaohao,$je,$tfrq,$remark);
            } elseif ($message_type=="QY"){//发送取药通知
                $open_id = $message["open_id"];
                $sick_no = $message["sick_no"];
                $pati_name = $message["pati_name"];
                $pres_name = $message["pres_name"];
                $je = $message["je"];
                //slog("openid=$open_id");
                $this->sendmessage_quyao($wxh,$open_id,$sick_no,$pati_name,$pres_name,$je);
            }
        }
        //判断时间，发送所有预约通知
        $time= date("Hi",time());
        if ($time>"1930"){
            $bookdate=date("Y-m-d",strtotime("+1 day"));
            // $bookdate="2015-05-04";
            $bookingdays = D("wx_bookingdaysendmessage")->where("bookingdate='$bookdate'")->select();
            if (count($bookingdays)==0){ //如果尚未发送
                $this->sendmessage_all_yygh($bookdate);
                $bookingdaysendmessage = D('wx_bookingdaysendmessage')->create();
                $bookingdaysendmessage["bookingdate"] = $bookdate;
                D('wx_bookingdaysendmessage')->add($bookingdaysendmessage);

            }
        }

/*
        //同步统计表
        $feeinSums = $requestdata["yb_feein_sum"];
        $feeinsum_sync = array();
        foreach ($feeinSums as $feeinsum) {
            $feeinsum_id= $feeinsum["id"];
            //die($feeinsum_id);
            $feeinsum_rq= $feeinsum["rq"];
            $feeinsum_ybbz= $feeinsum["ybbz"];
            $sync_feeinsums = D("sync_feein_sums")->where("rq='$feeinsum_rq' and ybbz='$feeinsum_ybbz'")->delete();
            //if (count($sync_feeinsums)>0){//如果该记录已存在
            //  $sync_feeinsums[0]->delete();
            //  die("deleted");
            //}
            D('sync_feein_sums')->create();
            $datanew = array();
            $datanew['rq'] = $feeinsum["rq"];
            $datanew['rc'] = $feeinsum["rc"];
            $datanew['ybbz']   = $feeinsum["ybbz"];
            $datanew['fee001'] = $feeinsum["fee001"];
            $datanew['fee002'] = $feeinsum["fee002"];
            $datanew['fee003'] = $feeinsum["fee003"];
            $datanew['fee004'] = $feeinsum["fee004"];
            $datanew['fee005'] = $feeinsum["fee005"];
            $datanew['fee006'] = $feeinsum["fee006"];
            $datanew['fee007'] = $feeinsum["fee007"];
            $datanew['fee008'] = $feeinsum["fee008"];
            $datanew['fee009'] = $feeinsum["fee009"];
            $datanew['fee010'] = $feeinsum["fee010"];
            $datanew['fee011'] = $feeinsum["fee011"];
            $datanew['fee012'] = $feeinsum["fee012"];
            $datanew['fee013'] = $feeinsum["fee013"];
            $datanew['total']  = $feeinsum["total"];
            $datanew['zxjjsbzf']  = $feeinsum["zxjjsbzf"];
            $datanew['jjwbxje']  = $feeinsum["jjwbxje"];
            $datanew['bzje']  = $feeinsum["bzje"];
            $datanew['zhzf']  = $feeinsum["zhzf"];
            $datanew['xjzf']  = $feeinsum["xjzf"];
            $datanew['updaterq']  =  date("Y-m-d H:i:s");
            D('sync_feein_sums')->add($datanew);

            $syncdata = array();
            $syncdata["id"]=$feeinsum_id;
            $feeinsum_sync[]=$syncdata;

        }
*/
        //同步体检表
        $examinechecks = $requestdata["examinecheck"];
        $examinecheck_sync = array();
        foreach ($examinechecks as $examinecheck) {
            $examinecheck_id= $examinecheck["id"];
            D("sync_examinecheck")->where("id=$examinecheck_id")->delete();
            //if (count($sync_feeinsums)>0){//如果该记录已存在
            //  $sync_feeinsums[0]->delete();
            //  die("deleted");
            //}
            D('sync_examinecheck')->create();
            $datanew = array();
            $datanew['id'] = $examinecheck["id"];
            $datanew['tjrq'] = $examinecheck["tjrq"];
            $datanew['xm'] = $examinecheck["xm"];
            $datanew['sfzh'] = $examinecheck["sfzh"];
            $datanew['address'] = $examinecheck["address"];
            $datanew['keshi1'] = $examinecheck["keshi1"];
            $datanew['keshi2'] = $examinecheck["keshi2"];
            $datanew['keshi3'] = $examinecheck["keshi3"];
            $datanew['keshi4'] = $examinecheck["keshi4"];
            $datanew['keshi5'] = $examinecheck["keshi5"];
            $datanew['keshi6'] = $examinecheck["keshi6"];
            $datanew['keshi7'] = $examinecheck["keshi7"];
            $datanew['note'] = $examinecheck["note"];
            D('sync_examinecheck')->add($datanew);

            $syncdata = array();
            $syncdata["id"]=$examinecheck_id;
            $examinecheck_sync[]=$syncdata;

        }
/*
        //同步患者信息
        $patients = $requestdata["patients"];
        $pati_sync = array();
        foreach ($patients as $patient) {
            $pati_id= $patient["pati_id"];
            $sync_patients = D("sync_patient")->where("pati_id=$pati_id")->select();
            if (count($sync_patients)>0){//该患者信息已存在
                $datanew = array();
                $datanew['pati_id'] = $patient["pati_id"];
                $datanew['pati_name'] = $patient["pati_name"];
                $datanew['sick_no'] = $patient["sick_no"];
                $datanew['po_sick_no'] = $patient["po_sick_no"];
                $datanew['sex'] = $patient["sex"];
                $datanew['birthday'] = $patient["birthday"];
                $datanew['firstdate'] = $patient["firstdate"];
                $datanew['telephone'] = $patient["telephone"];
                D('sync_patient')->save($datanew);

            }else {//创建新纪录
                D('sync_patient')->create();
                $datanew = array();
                $datanew['pati_id'] = $patient["pati_id"];
                $datanew['pati_name'] = $patient["pati_name"];
                $datanew['sick_no'] = $patient["sick_no"];
                $datanew['po_sick_no'] = $patient["po_sick_no"];
                $datanew['sex'] = $patient["sex"];
                $datanew['birthday'] = $patient["birthday"];
                $datanew['firstdate'] = $patient["firstdate"];
                $datanew['telephone'] = $patient["telephone"];
                D('sync_patient')->add($datanew);

            }
            $syncdata = array();
            $syncdata["pati_id"]=$pati_id;
            $pati_sync[]=$syncdata;
        }

        //查询患者变化，返回增加列表
        $pati_adds = D("wx_patient")->where("weixinhao='$wxh' and linktime>$synctime")->select();
        $pati_mins = D("wx_patient")->where("weixinhao='$wxh' and disabletime>$synctime")->select();
*/
        $return=Array();
        /*
        if ($pati_adds ) {
            $return["pati_adds"]=$pati_adds;
        }

        if ($pati_mins) {
            $return["pati_mins"]=$pati_mins;
        }
        if ($pati_sync) {
            $return["pati_sync"]=$pati_sync;
        }
        if ($feeinsum_sync) {
            $return["sync_feein_sums"]=$feeinsum_sync;
        }
        */
        //if ($examinecheck_sync) {
            $return["sync_examinechecks"]=$examinecheck_sync;
        //}
        $return["result"]="0";
        $return["message"]="成功,ok0";
        $return["synctime"]=time();
        die(json_encode($return));

    }




    /*

	    查找患者，由客户端调用，根据pati_id,查找患者信息，传回客户端
	    post数据
	    */
    public function querypatient()
    {
        //读取post过来的参数
        $postdata = urldecode(file_get_contents("php://input"));
        $requestdata = json_decode($postdata, TRUE);
        if (count($requestdata) == 0) {
            $result = array('result' => '-1', 'message' => '无数据提交', 'data' => $requestdata);
            exit(json_encode($result));
        }
        $md5str = $requestdata["md5str"];
        $wxh = $this->checkuser($md5str);
        //读取参数
        $pati_id = $requestdata["pati_id"];
        //查询患者
        $patients = D('wx_patient')->where("weixinhao='$wxh' and pati_id='".$pati_id."'")->select();
        if (count($patients)>0){
            $patient = $patients[0];
            $data = array();

            $data['message']="成功";
            $data['id']=$patient['id'];
            $data['pati_id']=$patient['pati_id'];
            $data['openid']=$patient['openid'];
            $data['pati_name']=$patient['pati_name'];
            $data['pati_sex']=$patient['pati_sex'];
            $data['sick_no']=$patient['sick_no'];
            $data['flag']=$patient['flag'];
            $data['linktime']=$patient['linktime'];
            if ($patient['openid']=='') {//绑定openid返回１
                $data['result'] = "0";
            } else {
                $data['result'] = "1";

            }
            $resultdata = json_encode($data);
            die($resultdata);
        } else {
            $data['result']="-20";
            $data['message']="没找到个人基本信息";
            die(json_encode($data));
        }
    }   /*

	    增加患者，由客户端调用，并请求微信服务器声成ticket，保存并将url传回客户端
	    post数据，传递以下参数 md5str,pati_id,pati_sex,pati_name,sick_no
	    */

    public function addpatient(){
        //读取post过来的参数
        $postdata = urldecode(file_get_contents("php://input"));
        $requestdata = json_decode($postdata,TRUE);
        if (count($requestdata) ==0){
            $result = array ('result'=>'-1','message'=>'无数据提交','data'=>$requestdata);
            exit(json_encode($result));
        }
        $md5str=$requestdata["md5str"];
        $wxh  = $this->checkuser($md5str);
        //读取参数
        $pati_id=$requestdata["pati_id"];
        $pati_sex=$requestdata["pati_sex"];
        $pati_name=$requestdata["pati_name"];
        $sick_no= $requestdata["sick_no"];
        //生成二维码
        $access = $this->getAccess($wxh);
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access;
        $data['expire_seconds'] = 1800;
        $data['action_name'] = 'QR_SCENE';
        $data['action_info']['scene']['scene_id'] = $pati_id;
        $jsondata = json_encode($data);
        $json=self::http_request_json_post($url,$jsondata);
        $returndata = json_decode($json,true);
        $ticket = $returndata['ticket'];

        //查询患者
        $patients = D('wx_patient')->where("weixinhao='$wxh' and sick_no='".$sick_no."'")->select();
        if (count($patients)>0){
            //需要判断用户是否已经关联
            $patient=$patients[0];
            $patient['ticket']=$ticket;
            D('wx_patient')->save($patient);
            if ($patient["flag"]=="1"){
                $json_result['result']="-1";
                $json_result['qrurl']=  "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;
                $json_result['ticket']=  $ticket;
                $json_result['message']="用户已经绑定微信号，请核对";
                $resultdata = json_encode($json_result);
                die($resultdata);
            }

        } else {
            // slog('创建新纪录');
            $patient = D('wx_patient')->create();
            $patient['weixinhao']=$wxh;
            $patient['pati_id']=$pati_id;
            $patient['pati_sex']=$pati_sex;
            $patient['pati_name']=$pati_name;
            $patient['sick_no']=$sick_no;
            $patient['flag']="0";
            $patient['ticket']=$ticket;
            D('wx_patient')->add($patient);
        }




        $json_result['qrurl']=  "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;
        $json_result['ticket']=  $ticket;
        $json_result['result'] = '0';
        $json_result['message'] = 'OK';

        $resultdata = json_encode($json_result);
        die($resultdata);
    }
    /* 创建菜单 */
    public function createmenu(){
        $data=Array("button"=> array(
            Array(
                'name'=>urlencode("经典案例"),
                'sub_button'=>Array(
                    Array(
                        'type'=>'click',
                        'name'=>urlencode('前列腺病症'),
                        'key'=>'key_qlxbz'
                    ),
                    Array(
                        'type'=>'click',
                        'name'=>urlencode('功能障碍'),
                        'key'=>'key_gnza'
                    ),
                    Array(
                        'type'=>'click',
                        'name'=>urlencode('不育不孕'),
                        'key'=>'key_byby'
                    ),
                    Array(
                        'type'=>'click',
                        'name'=>urlencode('腰腿颈椎'),
                        'key'=>'key_ytjz'
                    ),
                    Array(
                        'type'=>'click',
                        'name'=>urlencode('中医内科'),
                        'key'=>'key_zynk'
                    )
                )),
            Array(
                'name'=>urlencode("联系我们"),
                'sub_button'=>Array(
                    Array(
                        'type'=>'click',
                        'name'=>urlencode('免费咨询电话'),
                        'key'=>'key_mfzxdh'
                    ),
                    Array(
                        'type'=>'click',
                        'name'=>urlencode('QQ咨询'),
                        'key'=>'key_qqzx'
                    ),
                    Array(
                        'type'=>'view',
                        'name'=>urlencode('医院官网'),
                        'url'=>'http://www.doctorcao.com'
                    )
                )),
            Array(
                'name'=>urlencode("我的卡号"),
                'type'=>'click',
                'key'=>'key_mycard'
            )

        ));

        $myappid = 'gh_8eefc37aa888';
        $access = $this->getAccess($myappid);
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access;
        $jsondata =    urldecode(stripslashes(json_encode($data)));
        $json=self::http_request_json_post($url,$jsondata);
        //$returndata = urldecode(json_decode($json,true));
        die($json);


    }
    public function getWeixinhao($myid){
        $appdatas = D('appinfo')->where("id=".$myid)->select();
        $appdata = $appdatas[0];
        return $appdata['weixinhao'];
    }
    //取得当前myappid的access_token 函数方式
    public function getAccess($weixinhao){
        $appdatas = D('wx_appinfo')->where("weixinhao='$weixinhao'")->select();
        $appdata = $appdatas[0];
        $appid= $appdata['wxappid'];
        $secret= $appdata['secret'];
        $access_token= $appdata['access_token'];
        $expire = $appdata['expire'];
        if ($expire>time()){
            return $access_token;
        }

        $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $json=self::http_request_json($url);//这个地方不能用file_get_contents ，因为url是https
        $data=json_decode($json,true);
        if($data['access_token']){
            $appdata['expire']= time()+$data['expires_in']-600;
            $appdata['access_token']= $data['access_token'];
            D('wx_appinfo')->save($appdata);
            return $data['access_token'];
        }else{
            return "获取access_token错误";
        }
    }


    //取得当前myappid的access_token json方式
    public function getAccessToken(){
        $appid=I("appid");
        $access = $this->getAccess($appid);

        $appinfo = D('wx_appinfo')->where("access_token='$access'")->find();

        if ($access=="")	{
            $data['access'] = $access;
            $data['message'] = "无法获取accessToken";
            $data['result'] = "-1";
        } else {
            $data['message'] = "获取accesstoken成功";
            $data['result'] = "0";
            $data['access'] = $access;
            $data['serverip'] = $appinfo['serverip'];

        }
        die(json_encode($data));

    }
    public function checkuser($md5str){
        $users = D("wx_user")->where("md5str='$md5str'")->select();
        if (count($users)>0){
            $user= $users[0];
            return $user['weixinhao'];
        } else {
            $data['result']= "-10";
            $data['message']= "用户名或密码错，请重新登录,username or password wrong,please try again";
            die(json_encode($data));
        }

    }
    public function getUsername($md5str){
        $users = D("wx_user")->where("md5str='$md5str'")->select();
        if (count($users)>0){
            $user= $users[0];
            return $user['username'];
        } else {
            $data['result']= "-10";
            $data['message']= "用户名或密码错，请重新登录,username or password wrong,please try again";
            die(json_encode($data));
        }

    }
    //用户登录 json方式
    public function login(){
        /*
        Slog::config(array(
            'enable'=>true,//是否打印日志的开关
            'host'=>'slog.thinkphp.cn',//websocket服务器地址，默认localhost
            'optimize'=>false,//是否显示利于优化的参数，如果运行时间，消耗内存等，默认为false
            'show_included_files'=>false,//是否显示本次程序运行加载了哪些文件，默认为false
            'error_handler'=>false,//是否接管程序错误，将程序错误显示在console中，默认为false
            'force_client_id'=>'slog_9bc5eb',//日志强制记录到配置的client_id,默认为空
            'allow_client_ids'=>array()////限制允许读取日志的client_id，默认为空,表示所有人都可以获得日志。
        ));
        */
        //读取post过来的参数
        $postdata = urldecode(file_get_contents("php://input"));
        $requestdata = json_decode($postdata,TRUE);
        if (count($requestdata) ==0){
            $result = array ('result'=>'-1','message'=>'无数据提交','data'=>$requestdata);
            exit(json_encode($result));
        }
        $username=$requestdata["username"];
        $password=md5($requestdata["password"]);
       // Slog::big('password=$password');
        $users = D("wx_user")->where("username='$username' and password='$password'")->select();
        if (count($users)>0){

            $user=$users[0];
            $logintime = time();
            $md5str = md5("$username$password$logintime");
            $user['logintime'] = $logintime;
            $user['md5str'] = $md5str;
            D("wx_user")->save($user);
            $weixinhao = $user["weixinhao"];
            $appinfo = D('wx_appinfo')->where("weixinhao='$weixinhao'")->find();

            $data['result']="0";
            $data['message']="登录成功";
            $data['md5str']=$md5str;
            $data['weixinhao']=$weixinhao;
            $data['serverip']=$appinfo["serverip"];
            $data['access']=$this->getAccess($weixinhao);
            die(json_encode($data));
        } else {
            $data['result']="-10";
            $data['message']="登录失败，用户名或密码错,username or password wrong,please try again $password";
            die(json_encode($data));
        }
    }
    public function get_sync_ip(){
        if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]) {
            $ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
        } elseif ($HTTP_SERVER_VARS["HTTP_CLIENT_IP"]) {
            $ip = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
        } elseif ($HTTP_SERVER_VARS["REMOTE_ADDR"]) {
            $ip = $HTTP_SERVER_VARS["REMOTE_ADDR"];
        } elseif (getenv("HTTP_X_FORWARDED_FOR")) {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $ip = getenv("HTTP_CLIENT_IP");
        } elseif (getenv("REMOTE_ADDR")){
            $ip = getenv("REMOTE_ADDR");
        } else {
            $ip = "Unknown";
        }
        return $ip;

    }

    //因为url是https 所有请求不能用file_get_contents,用curl请求json 数据
    function http_request_json($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    function http_request_json_post($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}